<template>
  <!-- Banner -->
  <Banner :data="form" />
  {{ form }}
  <!-- 容器 -->
  <div class="container md:w-3/4 m-auto" v-if="form">
    <div class="flex flex-col">
      <Breadcrumb :data="form" />
      <div :class="form.design?.styles" class="page-main w-full bg-white rounded-lg">
        <div class="p-4 leading-7" v-html="form.design?.content">
        </div>
      </div>
    </div>
  </div>
  <div v-if="!form">
    <el-empty description="404 页面不存在"></el-empty>
  </div>
</template>
<script setup lang="ts">
import type {ApiResult} from "~/api";
import {useServerRequest} from "~/composables/useServerRequest";
import {useConfigInfo, useForm, useToken, useWebsite} from "~/composables/configState";
import Breadcrumb from "~/components/Breadcrumb.vue";
import type {BreadcrumbItem} from "~/types/global";
import type {Navigation} from "~/api/cms/navigation/model";

// 引入状态管理
const route = useRoute();
const website = useWebsite();
const config = useConfigInfo();
const token = useToken();
const form = useForm();
const breadcrumb = ref<BreadcrumbItem>();

// 请求数据
const reload = async () => {
  // 都不存在
  if(!form.value.navigationId && !form.value.path){
    return ;
  }

  // 存在spm(优先级高)
  if(form.value.navigationId){
    console.log('11111')
    const { data: nav } = await useServerRequest<ApiResult<Navigation>>('/cms/navigation/' + form.value.navigationId)
    if (nav.value?.data) {
      form.value = nav.value.data
    }
  }

  // 不存在spm的情况
  if(!form.value.navigationId){
    console.log('2222')
    const { data: nav } = await useServerRequest<ApiResult<Navigation>>('/cms/navigation/getNavigationByPath',{query: {path: form.value.path}})
    if(nav.value?.data){
      form.value = nav.value?.data;
    }
  }

  // seo
  useHead({
    title: `${form.value.title} - ${website.value.websiteName}`,
    meta: [{ name: form.value.design?.keywords, content: form.value.design?.description }],
    bodyAttrs: {
      class: "page-container",
    },
    script: [
      {
        children: `console.log(${JSON.stringify(form.value)})`,
      },
    ],
  });
  // 面包屑
  breadcrumb.value = form.value
}

watch(
    () => route.query.spm,
    (spm) => {
      // TODO 方案一(优先级高)：从spm参数提取商品ID
      if(spm){
        const spmValue = String(spm).split('.')
        if(spmValue[5]){
          form.value.navigationId = Number(spmValue[5])
        }
        return reload();
      }

      // TODO 方案二：从params获取商品ID
      const { custom } = route.params
      form.value.path = `/${custom}`;

      reload();
    },
    { immediate: true }
);
</script>
